package com.cy.demo.controller;


import com.cy.demo.controller.ex.*;
import com.cy.demo.service.ex.*;
import com.cy.demo.utils.jsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

//控制层类的基类
public class BaseController {
    public static final int OK = 200;

    //请求处理方法，这个方法的返回值就是需要传递给前端的数据
    //自动将异常对象传递给此方法的参数列表上
    //当项目中产生了异常，被统一拦截到此方法中，这个方法此时就充当请求处理方法
    @ExceptionHandler({ServiceException.class,FileUploadException.class})//用于统一处理抛出的异常
    public jsonResult<Void> handleException(Throwable e){
        jsonResult<Void> result = new jsonResult();
        if(e instanceof UsernameDulicateException){
            result.setState(4000);
            result.setMessage("用户名被占用！");
        }else if(e instanceof InsertException){
            result.setState(5000);
            result.setMessage("注册时产生未知异常！");
        }else if(e instanceof InformationUmptyException){
            result.setState(6000);
            result.setMessage("用户名或者密码为空!");
        }else if(e instanceof UsernameNotexistException){
            result.setState(7000);
            result.setMessage("用户名不存在！");
        }else if(e instanceof PasswordError){
            result.setState(8000);
            result.setMessage("密码不正确！");
        }else if(e instanceof PhoneEmpty){
            result.setState(8001);
            result.setMessage("手机号码为空！");
        }else if(e instanceof EmailEmpty){
            result.setState(8002);
            result.setMessage("邮箱为空！");
        }else if (e instanceof FileEmptyException) {
            result.setState(9000);
            result.setMessage("图片为空！");
        } else if (e instanceof FileSizeException) {
            result.setState(9001);
            result.setMessage("图片太大了！");
        } else if (e instanceof FileTypeException) {
            result.setState(9002);
            result.setMessage("图片格式不支持！");
        } else if (e instanceof FileStateException) {
            result.setState(9003);
            result.setMessage("请先关闭图片再上传！");
        } else if (e instanceof FileUploadIOException) {
            result.setState(9004);
        }

        return result;
    }

    /**
     * 获取Session对象中的uid
     * @param session session对象
     * @return 当前登录的用户uid的值
     */
    protected final Integer getuidFromSession(HttpSession session){

        return Integer.valueOf( session.getAttribute("uid").toString());
    }

    /**
     * 获取Session对象中的username
     * @param session session对象
     * @return 当前登录的用户username的值
     */
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
